package me.healthcare.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONObject;

import me.healthcare.activity.PatientActivity.getPatient;
import me.healthcare.app.R;
import me.healthcare.common.ActionBarUtils;
import me.healthcare.model.Patient;
import me.healthcare.webserivce.WebService;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class RegisterActivity extends Activity {
	String error_log = "";

	private EditText reg_fullname;
	private EditText reg_email;
	private EditText reg_password;
	private EditText reg_password_confirm;
	private EditText deviceId;
	private EditText doctorId;

	private TextView warningText;
	private TextView loginScreen;
	private TextView deviceIdText;
	private TextView doctorIdText;

	RadioGroup roleRadioGroup;
	Button regButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set View to register.xml
		setContentView(R.layout.register_screen);

		ActionBarUtils.remade(this,
				getResources().getString(R.string.activity_register));

		loadViews();

		// hide doctor group by default
		doctorIdText.setVisibility(View.GONE);
		doctorId.setVisibility(View.GONE);

		// view variables

		// Listening to Login Screen link
		loginScreen.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				RegisterActivity.this.finish();
			}
		});

		// Change form required information base on RadioButton
		roleRadioGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switchRole(RegisterActivity.this, checkedId);
					}
				});

		// Listening to register button
		regButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String name = reg_fullname.getText().toString();
				String email = reg_email.getText().toString();
				String password = reg_password.getText().toString();
				String password_confirm = reg_password_confirm.getText()
						.toString();
				String device_code = deviceId.getText().toString();
				String doctor_code = doctorId.getText().toString();

				String error_log = "";

				if (name.equals("")) {
					error_log += "Bạn chưa điền tên\n";
				}
				if (email.equals("")) {
					error_log += "Bạn chưa điền email\n";
				}
				if (password.equals("")) {
					error_log += "Bạn chưa điền mật khẩu\n";
				}
				if (!password.equals(password_confirm)) {
					error_log += "Mật khẩu chính và mật khẩu xác nhận không trùng nhau\n";
				}
				if (password_confirm.equals("")) {
					error_log += "Bạn chưa điền xác nhận mật khẩu \n";
				}
				if (device_code.equals("") && doctor_code.equals("")) {
					error_log += "Bạn chưa điền mã kích hoạt\n";
				}

				if (error_log.equals("")) {

					String pass = reg_password.getText().toString();
					String sex = "nu";
					String dienthoai = "0987660162";
					String diachi = "jhfudsahgfuidhgjsdb";
					new dangKiBenhNhan()
							.execute("http://"
									+ WebService.HOST_IP
									+ "/sworldwebservice/sworld/auth/InsertPatients/12345/"
									+ pass + "/" + email + "/" + name + "/"
									+ sex + "/" + dienthoai + "/" + diachi);
				} else {
					warningText.setText("Lỗi:\n" + error_log);
					error_log = "";
				}
			}
		});

	}

	private void loadViews() {
		reg_fullname = (EditText) findViewById(R.id.reg_fullname);
		reg_email = (EditText) findViewById(R.id.reg_email);
		reg_password = (EditText) findViewById(R.id.reg_password);
		reg_password_confirm = (EditText) findViewById(R.id.reg_password_confirm);
		deviceId = (EditText) findViewById(R.id.reg_device_id);
		doctorId = (EditText) findViewById(R.id.reg_doctor_id);

		warningText = (TextView) findViewById(R.id.validate_errors);
		deviceIdText = (TextView) findViewById(R.id.reg_device_id_label);
		doctorIdText = (TextView) findViewById(R.id.reg_doctor_id_label);
		loginScreen = (TextView) findViewById(R.id.link_to_login);

		roleRadioGroup = (RadioGroup) findViewById(R.id.radioRole);
		regButton = (Button) findViewById(R.id.reg_register_button);

	}

	private void switchRole(Activity activity, int checkedId) {

		if (checkedId == R.id.radioNguoiDung) {
			deviceIdText.setVisibility(View.VISIBLE);
			deviceId.setVisibility(View.VISIBLE);
			doctorIdText.setVisibility(View.GONE);
			doctorId.setVisibility(View.GONE);
		} else if (checkedId == R.id.radioBacSi) {
			deviceIdText.setVisibility(View.GONE);
			deviceId.setVisibility(View.GONE);
			doctorIdText.setVisibility(View.VISIBLE);
			doctorId.setVisibility(View.VISIBLE);
		}
	}

	class dangKiBenhNhan extends AsyncTask<String, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected Boolean doInBackground(String... data) {
			try {
				URL url = new URL(data[0]);
				Log.d("URL", url.toString());
				URLConnection jc;

				jc = url.openConnection();
				InputStream is = jc.getInputStream();

				// doc du lieu
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				String jsonTxt = sb.toString(); // doc StringBuilder vao chuoi
				JSONObject jj = new JSONObject(jsonTxt);
				String status = jj.getString("status");
				JSONObject obj = jj.getJSONObject("obj");
				Log.d("toan", "trang thai " + status);

				if (!status.equalsIgnoreCase("SUCCESS")) {
					return false;
				}

			} catch (Exception e) {
				Log.d("ERROR", e.toString());
				return false;
			}
			return true;
		}

		protected void onPostExecute(Boolean id) {
			Toast.makeText(RegisterActivity.this,
					"Bạn đã đăng ký thành công tài khoản HealthCare",
					Toast.LENGTH_LONG).show();
			error_log = "";
		}
	}
}